package com.example.mq.client;

import com.example.mq.common.*;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Connection {
    private Socket socket = null;
    private ConcurrentHashMap<String, Channel> channelMap = new ConcurrentHashMap<>();
    private InputStream inputStream;
    private OutputStream outputStream;
    private DataInputStream dataInputStream;
    private DataOutputStream dataOutputStream;
    private ExecutorService callbackPool = null;

    public Connection(String host, int port) throws IOException {
        socket = new Socket(host, port);
        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();
        dataInputStream = new DataInputStream(inputStream);
        dataOutputStream = new DataOutputStream(outputStream);
        callbackPool = Executors.newFixedThreadPool(4);

        // 处理客户端接收到服务器的响应
        Thread t = new Thread(() -> {
            try {
                while (!socket.isClosed()) {
                    Response response = readResponse();
                    // 区分这个响应是控制请求的响应还是推送消息的响应
                    dispatchResponse(response);
                }
            } catch (SocketException e) {
                System.out.println("[Connection] 连接正常断开！");
            } catch (IOException | ClassNotFoundException | MqException e) {
                System.out.println("[Connection] 连接异常断开！");
                e.printStackTrace();
            }
        });
        t.start();
    }

    public void close() {
        try {
            callbackPool.shutdownNow();
            channelMap.clear();
            inputStream.close();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void dispatchResponse(Response response) throws IOException, ClassNotFoundException, MqException {
        if (response.getType() == 0xc) {
            // 表示响应是消息推送
            SubscribeReturns subscribeReturns = (SubscribeReturns) BinaryTool.fromBytes(response.getPayload());
            // 根据channelId找到对应的回调
            Channel channel = channelMap.get(subscribeReturns.getChannelId());
            if (channel == null) {
                throw new MqException("[Connection] 该消息对应的 Channel 在客户端不存在！ channelId = " +subscribeReturns.getChannelId());
            }
            callbackPool.submit(()->{
                try {
                    channel.getConsumer().handleDelivery(subscribeReturns.getConsumerTag(), subscribeReturns.getBasicProperties(),
                            subscribeReturns.getBody());
                } catch (MqException | IOException e) {
                    e.printStackTrace();
                }
            });
        } else {
            // 表示针对控制请求的响应
            BasicReturns basicReturns = (BasicReturns) BinaryTool.fromBytes(response.getPayload());
            Channel channel = channelMap.get(basicReturns.getChannelId());
            if (channel == null) {
                throw new MqException("[Connection] 该消息对应的 Channel 在客户端不存在！ channelId = " + basicReturns.getChannelId());
            }
            // 将响应添加到channel的存放所有响应的哈希表中
            channel.putReturns(basicReturns);
        }
    }

    // 客户端发送请求
    public void writeRequest(Request request) throws IOException {
        dataOutputStream.writeInt(request.getType());
        dataOutputStream.writeInt(request.getLength());
        dataOutputStream.write(request.getPayload());
        dataOutputStream.flush();
        System.out.println("[Connection] 发送请求！ type = " + request.getType() + ",length = " + request.getLength());
    }

    // 客服端读取服务器返回的响应
    public Response readResponse() throws IOException {
        Response response = new Response();
        response.setType(dataInputStream.readInt());
        response.setLength(dataInputStream.readInt());
        byte[] payload = new byte[response.getLength()];
        int n = dataInputStream.read(payload);
        if (n != response.getLength()) {
            throw new IOException("读取响应数据不完整！");
        }
        response.setPayload(payload);
        System.out.println("[Connection] 收到响应 type = " + response.getType() + ",length = " + response.getLength());
        return response;
    }

    // 创建一个channel
    public Channel createChannel() throws IOException {
        // channel的唯一id
        String channelId = "C-" + UUID.randomUUID().toString();
        Channel channel = new Channel(channelId, this);
        channelMap.put(channelId, channel);
        // 同时创建成功也要将结果告知服务器
        boolean ok = channel.createChannel();
        if (!ok) {
            // 服务器创建失败，
            channelMap.remove(channelId);
            return null;
        }
        return channel;
    }
}
